package rt.crashmere.sdk.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import rt.crashmere.sdk.model.SDKUser;
import rt.crashmere.sdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用api的客户端
 *
 * @author Lwh
 * @time 2023/01/22 21:43
 */
public class ApiClient {

    private final String GATEWAY_HOST;
    private final String accessKey;
    private final String secretKey;

    public ApiClient(String accessKey, String secretKey, String host) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.GATEWAY_HOST = "http://" + host;
    }

    public String getUsernameByJson(String username) {
        SDKUser user = new SDKUser(username);
        String json = JSONUtil.toJsonStr(user);
        HttpResponse response = HttpRequest.post(GATEWAY_HOST + "/api/user/username")
                .addHeaders(getHeaderMap())
                .body(json)
                .execute();
        int status = response.getStatus();
        if (status == 200) {
            return response.body();
        }
        return null;
    }

    private Map<String, String> getHeaderMap() {
        Map<String, String> map = new HashMap<>();
        map.put("accessKey", accessKey);
        map.put("sign", SignUtils.genSign(secretKey, accessKey));
        map.put("nonce", RandomUtil.randomNumbers(10));
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        return map;
    }

}
